import redis
from config import REDIS_CONFIG


class RedisPool(object):
    """redis连接池"""

    # 连接池对象
    __pool = None

    def __init__(self):
        if RedisPool.__pool is None:
            RedisPool.__pool = redis.ConnectionPool(
                host=REDIS_CONFIG['host'],
                password=REDIS_CONFIG['password'],
                port=REDIS_CONFIG['port'],
                db=REDIS_CONFIG['db']
            )
            print("建立redis连接池...")
        # 连接redis
        self.conn = redis.Redis(connection_pool=RedisPool.__pool)

    def set_key(self, key, value, time=None):

        """
        redis 存储str类型数据
        Args:
          key: string
          value: int/string
        """
        if time:
            # ex: 秒
            # px: 毫秒
            res = self.conn.set(key, value, ex=time)
        else:
            res = self.conn.set(key, value)
        return res

    def get_key(self, key):
        """
        获取str类型数据
        :param key:
        :return:
        """
        res = self.conn.get(key)
        if res is not None:
            return res.decode()
        return res

    def hset(self, key, attr, value):
        """
        存储hash类型数据， 单个数据
        Args:
          key: 键名
          value: 值
        """
        res = self.conn.hset(key, attr, value)
        return res

    def hmset(self, key, obj):
        """
        储存hash类型数据， 多个数据
        Args:
          key: 键名
          obj: mapping对象
        """
        res = self.conn.hmset(key, obj)
        return res

    def hget(self, key, attr):
        """获取hash类型数据， 单个数据"""
        res = self.conn.hget(key, attr)
        if res:
            return res.decode()
        return res

    def hgetall(self, key):
        """获取hash类型数据，多个数据"""
        res = self.conn.hgetall(key)
        return res

    def del_key(self, key):
        """删除键"""
        res = self.conn.delete(key)
        return res

    def expire(self, key, second):
        """
        设置某个键过期时间
        Args:
          key: string, 键
          second: int, 过期时间, 秒
        """
        res = self.conn.expire(key, second)
        return res
